<template>
  <div>
    <div ref="chartContainer" :style="{ width: '100%', height: '300px' }" />
  </div>
</template>

<script setup>
import { dataURLtoBlob } from "@/utils/common";
import * as echarts from "echarts";
import { computed, onUnmounted, ref, watch } from "vue";
import { useRouter } from "vue-router";
const router = useRouter();

const chartContainer = ref(null);
let chartInstance = null;
const props = defineProps({
  chartsData: {
    type: Object,
    required: true
  },
  className: {}
});

const options = computed(() => {
  return {
    color: ["#E02B2B", "#FF771E", "#F1B11A", "#4A9BFF"],
    tooltip: {
      trigger: "axis"
    },
    legend: {
      data: ["一级报警", "二级报警", "三级报警", "四级报警"]
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      data: props.chartsData.alarmTrendTime
    },
    yAxis: {
      type: "value"
    },
    series: [
      {
        data: props.chartsData.firstAlarmTrendVal,
        type: "line",
        name: "一级报警"
      },
      {
        data: props.chartsData.secondAlarmTrendVal,
        type: "line",
        name: "二级报警"
      },
      {
        data: props.chartsData.thirdAlarmTrendVal,
        type: "line",
        name: "三级报警"
      },
      {
        data: props.chartsData.fourthAlarmTrendVal,
        type: "line",
        name: "四级报警"
      }
    ]
  };
});
const initChart = () => {
  if (chartContainer.value) {
    chartInstance = echarts.init(chartContainer.value);
    chartInstance.setOption(options.value);
    chartInstance.on("click", params => {
      const { startTime, endTime } = props.chartsData;
      router.push(
        `/all/alert/business?className=${props.className}&alarmLevel=${params.seriesName}&active=ALL&startTime=${startTime}&endTime=${endTime}`
      );
    });
  }
};

watch(
  () => props.chartsData,
  chartsData => {
    initChart();
  }
);

const downLoad = () => {
  const img64 = chartInstance.getDataURL({
    type: "png",
    pixelRatio: 2,
    backgroundColor: "#fff"
  });
  const blob = dataURLtoBlob(img64);
  const imgSrc = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = imgSrc;
  link.style.display = "none";
  link.setAttribute("download", "报警时间趋势");
  document.body.appendChild(link);
  link.click();
  URL.revokeObjectURL(link.href);
  document.body.removeChild(link);
};

defineExpose({
  downLoad
});

onUnmounted(() => {
  chartInstance && chartInstance.dispose();
});
</script>
